package com.chennan.websocket.domain;

import com.chennan.websocket.domain.model.User;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.stereotype.Component;
import sun.security.pkcs11.wrapper.Constants;

import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author chennan
 * @createTime 2021年08月02日 10:48:00
 * User 拦截器
 */
public class UserInterceptor implements ChannelInterceptor {
    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
//        Map<String, Object> sessionAttributes = accessor.getSessionAttributes();
//        String host = accessor.getHost();
//        Principal user1 = accessor.getUser();
        List<String> nativeHeader=accessor.getNativeHeader("name");
        String name =null;
        if(nativeHeader!=null){
            name = nativeHeader.get(0);
        }

//        MessageHeaders messageHeaders = accessor.getMessageHeaders();
//        Map nativeHeaders = (Map)messageHeaders.get("nativeHeaders");
//        Object name1 = nativeHeaders.get("name");
        if (StompCommand.CONNECT.equals(accessor.getCommand())) {
//            User user = (User)accessor.getSessionAttributes().get(Constants.WEBSOCKET_USER_KEY);
            User user = new User();
            user.setUsername(name);
            accessor.setUser(user);
        }
        return message;
    }

    @Override
    public void postSend(Message<?> message, MessageChannel channel, boolean sent) {

    }

    @Override
    public void afterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, Exception ex) {

    }

    @Override
    public boolean preReceive(MessageChannel channel) {
        return false;
    }

    @Override
    public Message<?> postReceive(Message<?> message, MessageChannel channel) {
        return null;
    }

    @Override
    public void afterReceiveCompletion(Message<?> message, MessageChannel channel, Exception ex) {

    }
}
